<template>
  <div class="app-box">
    <!-- 头部操作栏for桌面端 -->
    <!-- <div id="head-control">
      <div class="button-group">
        <van-icon name="minus" />
        <van-icon name="cross" />
      </div>
    </div> -->
    <!-- 头部区域 -->
    <div id="header">
      <div class="header-title2">
        <van-nav-bar title="Music">
          <template #left v-if="!isIndex">
            <van-icon name="arrow-left" color="white" />
            <span @click="back">返回</span>
          </template>
          <template #right>
            <van-icon id="searchBtn" name="search" size="18" color="white" @click="showSearch" />
          </template>
        </van-nav-bar>
      </div>
      <!-- 搜索框 -->
      <transition name="search" mode="out-in">
        <van-search
          v-model="keyword"
          background="red"
          input-align="center"
          shape="round"
          placeholder="请输入搜索关键词"
          left-icon
          show-action
          :clearable="false"
          @blur="onCancel"
          @search="onSearch"
          v-show="searchFlag"
        >
          <template #action>
            <div @click="onSearch">
              <a>搜索</a>
            </div>
          </template>
        </van-search>
      </transition>
    </div>

    <!-- 中间路由router-view区域 -->
    <router-view
      :cookie="cookie"
      :SongsList="SongsList"
      :VideoList="VideoList"
      :SingerList="SingerList"
      :keyword="keyword"
      :SearchSongsHasmore="SearchSongsHasmore"
      :SearchVideosHasmore="SearchVideosHasmore"
      :SearchSingerHasmore="SearchSingerHasmore"
      :reset="reset"
      :PlayingList="PlayingList"
      @clickSong="clickSong"
      @clickCollection="clickCollection"
      @getSongPic="getSongPic"
      class="middle-view"
    ></router-view>
    <!-- 固定的背景图片 -->
    <!-- <div id="background"></div> -->

    <!-- 底部的播放控件 -->
    <transition name="musicPlayer">
      <music-player
      :PlayingSongDetail="PlayingSongDetail"
      :musicFlag="musicFlag"
      @playMusic="playMusic"
      @fullScreen="fullScreen"
      @nextOrBefore="nextOrBefore"
       v-if="musicFlag"
      ></music-player>
    </transition>
    <!-- 全屏模态框盒子 -->
    <transition name="full">
      <full-screen 
      :PlayingSongDetail="PlayingSongDetail"
      :progressBar="progressBar"
      :fullscreenFlag="fullscreenFlag"
      @backFullscreen="backFullscreen"
      @playMusic="playMusic"
      @nextOrBefore="nextOrBefore"
       v-if="fullscreenFlag"
      ></full-screen>
    </transition>
  </div>
</template>

<script>
import { Notify } from "vant";
import $ from "jquery";
// 导入全屏组件
import fullScreen from './components/fullScreen.vue';
// 导入音乐控制组件
import musicPlayer from './components/musicPlayer.vue'
export default {
  data: function() {
    return {
      cookie: "",
      selected: "",
      //  searchFlag是否展示搜索框
      searchFlag: false,
      // musicFlag控制是否展示播放控件
      musicFlag: false,
      // 是否全屏
      fullscreenFlag: false,
      //是否打开评论
      commentFlag: false,
      keyword: "",
      // 保存搜索的结果
      SongsList: [],
      VideoList: [],
      SingerList: [],
      //是否有更多歌曲
      SearchSongsHasmore: false,
      // 是否有更多视频
      SearchVideosHasmore: false,
      // 是否有更多歌手
      SearchSingerHasmore: false,
      // 用于重置偏移量offset
      reset: false,
      // 正在播放的歌曲列表
      PlayingList: [],
      //正在播放的歌曲详情
      PlayingSongDetail: {
        songId: "",
        SongName: "",
        SingerName: "",
        url: "",
        picUrl: "",
        size: "",
        currentTime: "",
        lyric:[],
        tlyric:"",
      },
      // 获取当前播放进度的计时器
      musicTimer: {},
      // 进度条对象
      progressBar: {
        size: "",
        currentTime: "",
        outside_width: "280",
        inside_width: ""
      },
      // 定时器audio
      tempTimer: {},
      // 当前路由地址
      isIndex:false,
    };
  },
  methods: {
    //返回上一页
    back() {
      this.$router.go(-1);
    },
    // 点击全屏
    fullScreen() {
      this.fullscreenFlag = true;
      // 设置控制栏变色
      // $("#head-control").css("background","cornflowerblue")
    },

    // 退出全屏
    backFullscreen() {
      this.fullscreenFlag = false;
      // $("#head-control").css("background","red")
    },

    // 展示搜索框的方法
    showSearch() {
      this.searchFlag = !this.searchFlag;

      if (this.searchFlag == false) {
        document.getElementById("searchBtn").className =
          "van-icon van-icon-search";
      } else {
        document.getElementById("searchBtn").className =
          "van-icon van-icon-arrow-up";
      }
    },

    //取消搜索框
    onCancel() {
      this.searchFlag = !this.searchFlag;
      document.getElementById("searchBtn").className =
        "van-icon van-icon-search";
    },

    // 搜索事件
    onSearch() {
      this.searchFlag = false;
      this.reset = !this.reset;
      // 如果输入为空,返回
      if (this.keyword.trim().length == 0) {
        return false;
      }
      // 发送请求
      //搜索单曲
      this.$http.get("search?type=1&keywords=" + this.keyword).then(result => {
        console.log(result);
        // console.log(result.data);
        Notify({ type: "success", message: "搜索成功", duration: 500 });
        this.SongsList = result.data;
        // 设置SearchSongsHasmore的值
        this.SearchSongsHasmore = result.data.result.hasMore;
      });
      //搜索视频1014
      this.$http
        .get("search?limit=8&type=1014&keywords=" + this.keyword)
        .then(result => {
          // console.log(result);
          // console.log(result.data);
          this.VideoList = result.data.result;
          // 设置SearchVideosHasmore的值
          this.SearchVideosHasmore = result.data.result.hasMore;
        });
      //搜索歌手100
      this.$http
        .get("search?limit=8&type=100&keywords=" + this.keyword)
        .then(result => {
          // console.log(result);
          // console.log(result.data);
          this.SingerList = result.data.result;
          // 路由重定向
          // console.log(this.$route.path);
          // 设置SearchSingerHasmore的值
          this.SearchSingerHasmore = result.data.result.hasMore;
          if (this.$route.path != "/searchList")
            this.$router.push("/searchList");
        });
    },

    // 获取点击后的歌曲id,子组件向父组件传值
    clickSong(id, SongName, SingerName) {
      //更新正在播放歌曲详情
      this.PlayingSongDetail.songId = id;
      this.PlayingSongDetail.SongName = SongName;
      this.PlayingSongDetail.SingerName = SingerName;
      this.PlayingSongDetail.url =
        "https://music.163.com/song/media/outer/url?id=" + id;
      console.log(this.PlayingSongDetail.url);
      //添加获取播放列表
      this.PlayingList = [];
      this.SongsList.result.songs.forEach((item, index) => {
        this.PlayingList.push({
          index: index,
          id: item.id,
          name: item.name,
          singer: item.artists[0].name,
          url:
            "https://music.163.com/song/media/outer/url?id=" + item.id + ".mp3",
          picId: item.album.id
        });
      });
      // 找到当前歌曲下标
      this.PlayingList.forEach(item => {
        if (item.id == id) {
          this.PlayingSongDetail.index = item.index;
          // 查看是否有版权
          this.$http
            .get("check/music?id=" + this.PlayingSongDetail.songId)
            .then(
              result => {},
              error => {
                this.nextOrBefore("next");
                Notify({
                  type: "warning",
                  message: "暂无版权",
                  duration: 1000
                });
              }
            );
        }
      });
      // 获取歌曲长度，当前播放指针
      // 此处使用定时器获取audio，避免刚开始时audio为空
      this.tempTimer = setInterval(this.TimerFunc, 1000);
    },

    //点击歌单详情播放
    clickCollection(id, SongName, SingerName, picId, lyric, collectionList) {
      //更新正在播放歌曲详情
      this.PlayingSongDetail.songId = id;
      this.PlayingSongDetail.SongName = SongName;
      this.PlayingSongDetail.SingerName = SingerName;
      this.PlayingSongDetail.url =
        "https://music.163.com/song/media/outer/url?id=" + id;

      // this.PlayingSongDetail.lyric = lyric;
      //更新播放列表
      this.PlayingList = collectionList;
      // 找到当前歌曲下标
      this.PlayingList.forEach(item => {
        if (item.id == id) {
          this.PlayingSongDetail.index = item.index;
          // 查看是否有版权
          this.$http.get("check/music?id=" + id).then(
            result => {},
            error => {
              this.nextOrBefore("next");
              Notify({ type: "warning", message: "暂无版权", duration: 1000 });
            }
          );
        }
      });
      //展示播放控件
      this.musicFlag = true;
      // 获取歌曲长度，当前播放指针
      // 此处使用定时器获取audio，避免刚开始时audio为空
      this.tempTimer = setInterval(this.TimerFunc, 1000);
      //更新封面
      this.getSongPic(picId);
    },

    // 获取封面,需要通过获取专辑封面
    getSongPic(album_id) {
      //通过专辑id获取封面
      this.$http.get("album?id=" + album_id).then(result => {
        this.PlayingSongDetail.picUrl = result.data.songs[0].al.picUrl;
        this.musicFlag = true;
      });
    },

    // 获取歌词
    getLyric(id){
      this.$http.get(`lyric?id=${id}`).then(res=>{
        let lyric = res.body.lrc.lyric
          // console.log(lyric)
        lyric = lyric.split('\n')
        // 去除最后一个
        lyric.pop()
        // 检测是否有歌词
        if(lyric.length <= 2){
          this.PlayingSongDetail.lyric = [{second:0,lyric:"暂无歌词"}]
          return new Promise(()=>{})
        } 

        lyric = lyric.map(item=>{
          // 正则表达取出时间
          let time = /\[(.*?)\]/.exec(item)[1]
          // 将时间转化为秒
          let second = parseInt(time.split(':')[0])*60 + parseFloat(time.split(':')[1])
          // 取出歌词
          let lyric = item.split(']')[1]
          return {second, lyric}
        })
        // 赋值
        this.PlayingSongDetail.lyric = lyric
      })

    },

    // 点击播放音乐事件
    playMusic() {
      var playBtn = $(".playBtn ");
      var audio = document.getElementById("audio");
      // 增加 padding 防止遮挡页面
      $(".middle-view").css("padding-bottom","55px")
      //控制播放与暂停
      if (audio.paused) {
        audio.play();
        $(".playBtn ").attr("class", " glyphicon glyphicon-pause playBtn");
        // 播放时打开定时器
        clearInterval(this.musicTimer);
        this.musicTimer = setInterval(this.musicTimerFunc, 500);
      } else {
        audio.pause();
        $(".playBtn ").attr("class", " glyphicon glyphicon-play playBtn");
        // 暂停时，停止定时器
        clearInterval(this.musicTimer);
      }
    },

    //控制上一首或下一首歌
    nextOrBefore(flag) {
      // 判断是上一首还是下一首
      if (flag == "next") {
        this.PlayingSongDetail.index++;
      } else {
        this.PlayingSongDetail.index--;
      }
      // 判断是否越界
      if (
        this.PlayingSongDetail.index > this.PlayingList.length ||
        this.PlayingSongDetail.index < 0
      ) {
        if (flag == "next") this.PlayingSongDetail.index--;
        else this.PlayingSongDetail.index++;
        Notify({ type: "success", message: "没有更多的了", duration: 500 });
        return false;
      }
      // 给当前的PlayingSongDetail更新值
      this.PlayingSongDetail.songId = this.PlayingList[
        this.PlayingSongDetail.index
      ].id;
      this.PlayingSongDetail.SongName = this.PlayingList[
        this.PlayingSongDetail.index
      ].name;
      this.PlayingSongDetail.SingerName = this.PlayingList[
        this.PlayingSongDetail.index
      ].singer;
      this.PlayingSongDetail.url = this.PlayingList[
        this.PlayingSongDetail.index
      ].url;
      //更新封面图片
      this.getSongPic(this.PlayingList[this.PlayingSongDetail.index].picId);
      // 查看是否有版权
      this.$http.get("check/music?id=" + this.PlayingSongDetail.songId).then(
        result => {},
        error => {
          this.nextOrBefore("next");
          Notify({ type: "warning", message: "暂无版权", duration: 1000 });
        }
      );
      //重新打开tempTimer定时器
      clearInterval(this.tempTimer);
      this.tempTimer = setInterval(this.TimerFunc, 1000);
    },

    // 更新进度条
    setProgressBar() {
      // 获取鼠标位置
      let length = event.clientX - outside.offsetLeft;
      // 计算currentTime
      let audio = document.getElementById("audio");
      audio.currentTime =
        (length / this.progressBar.outside_width) * this.PlayingSongDetail.size;
    },

    // 音乐定时器函数
    TimerFunc() {
      var audio = document.getElementById("audio");
      let size_second = parseInt(audio.duration);
      if (!isNaN(audio.duration)) {
        this.PlayingSongDetail.size = audio.duration;
        this.progressBar.size =
          parseInt(size_second / 60) + "." + (size_second % 60);
        clearInterval(this.musicTimer);
        this.musicTimer = setInterval(this.musicTimerFunc, 500);
        clearInterval(this.tempTimer);
      }
    },

    //获取播放进度的计时器函数
    musicTimerFunc() {
      // console.log("播放中");
      let audio = document.getElementById("audio");
      let size_second = parseInt(audio.duration);
      let currentTime_second = parseInt(audio.currentTime);
      // 判断是否到达音乐末尾，如果结束则播放下一首
      if (audio.ended) {
        this.nextOrBefore("next");
      }
      this.progressBar.currentTime =
        parseInt(currentTime_second / 60) + "." + (currentTime_second % 60);
      this.PlayingSongDetail.currentTime = audio.currentTime;
      //计算进度条长度
      this.inside_width =
        (currentTime_second / size_second) * this.progressBar.outside_width;
      if (this.inside_width < 20) {
        $("#inside").css("width", "20px");
      } else {
        $("#inside").css("width", this.inside_width + "px");
      }
    },



    // ❤音乐
    like(id) {
      this.$http.get("like?id=" + id + "&like=true").then(result => {
        console.log(result);
      });
    },

    messageBox() {
      MessageBox("提示", "操作成功");
    },
    getcookie() {},
    getcookie2() {}
  },
  watch: {
    //监测播放音乐的当前时间currentTime
    "PlayingSongDetail.currentTime": function(newValue) {},
    // 监听路由变化
    '$route.path':function(newValue){
      console.log(newValue)
      if(newValue == '/index'){
        console.log(this.isIndex)
        this.isIndex=true
      }else{
        this.isIndex=false
      }
    },
    // 监听歌曲详情变化
    "PlayingSongDetail.songId":function(newValue){
      // 获取歌词
      this.getLyric(newValue)
    },
    // // 监听歌词变化
    // "PlayingSongDetail.currentTime":function(newValue){
    //   this.PlayingSongDetail.lyric.forEach((item,index)=>{
    //     // 判断是否到达歌词的时间
    //     if(item.second < newValue){
    //       this.targetLyricIndex = index
    //       return
    //     }
    //   })
    //   console.log(this.targetLyricIndex)      
    // }
  },
  components: {
    // 通知组件
    [Notify.Component.name]: Notify.Componentm,
    // 全屏组件
    fullScreen,
    // 音乐播放器组件
    musicPlayer
  },
  mounted() {
    this.cookie = localStorage.getItem("cookie");
    // 监听路由变化
      if(this.$route.path == '/index'){
        this.isIndex=true
      }else{
        this.isIndex=false
      }
  }
};
</script>

<style lang="scss">
// 头部样式
.app-box {
  // 头部操作栏样式
  #head-control{
    height: 30px;
    width: 100%;
    background-color: red;
    position: fixed;
    top:0;
    z-index: 1000;
    -webkit-app-region:drag;
    .button-group{
      float: right;
      color:white;
      font-size: 1.5em;
      i{
        margin-right: 10px;
        -webkit-app-region:nodrag;
      }
    }
  }
  margin-top: 40px;
  .van-nav-bar__content {
    background: red;
    position: fixed;
    width: 100%;
    height: 40px;
    top: 0;
    z-index: 100;
  }
  .header-title2 {
    color: white;
    .van-ellipsis {
      color: white;
    }
  }
  #header {
    // 搜索框样式
    .van-field__control {
      background: white;
      border-radius: 15px;
      height: 30px;
      font-size: 12px;
    }
    .van-search {
      width: 100%;
      z-index: 100;
      height: 44px;
      margin: 0;
      top: 40px;
      padding: 0 18px;
      position: fixed;
    }
    .van-cell {
      padding: 0;
      margin: 0;
    }
    .van-search__action {
      a {
        color: white;
      }
    }
    .van-search__content {
      height: 30px;
      padding: 0;
      margin: 0;
    }
  }
  #middle {
    width: 100%;
    height: 100%;
    // padding-bottom: 55px;
    .lunbo {
      .van-swipe__track {
        height: 145.9px;
      }
    }
  }
  #background {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    background: url("./images/background.jpeg");
    background-size: 100%;
    z-index: -10;
  }
}

// 动画控制
.search-enter,
.search-leave-to {
  opacity: 0;
  transform: translateY(-100px);
}

.search-enter-active,
.search-leave-active {
  transition: all 0.5s ease;
}

//播放器动画
.musicPlayer-enter,
.musicPlayer-leave-to {
  opacity: 0;
  transform: translateY(55px);
}

.musicPlayer-enter-active,
.musicPlayer-leave-active {
  transition: all 0.5s ease;
}
// 全屏动画
.full-enter,
.full-leave-to {
  opacity: 0;
  transform: translateY(100%);
}

.full-enter-active,
.full-leave-active {
  transition: all 0.5s ease;
}
</style>
